import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getUUID } from "./uuid";

NProgress.configure({ showSpinner: false });

// 所有错误对象
const messages = {
  401: "未授权",
  403: "禁止访问",
  404: "资源找不到",
  500: "服务器内部错误",
};
const request = axios.create({
  baseURL: "/api",
  timeout: 5000,
  headers: {},
});

request.interceptors.request.use((config) => {
  NProgress.start();
  config.headers.userTempId = getUUID();
  //获取localStorage上的user
  const user = JSON.parse(localStorage.getItem("user"));
  console.log("user数据=>>", user);

  // 如果有user数据
  if (user) {
    // 在请求头中添加token数据
    config.headers.token = user.token;
  }
  return config;
});
request.interceptors.response.use(
  (res) => {
    NProgress.done();
    if (res.status === 200) {
      return res.data.data;
    } else {
      return Promise.reject(res.data.message || "未知错误,请联系管理员");
    }
  },
  (err) => {
    NProgress.done();
    let message = "未知错误,请联系管理员";
    //请求回来了
    if (err.response) {
      message = messages[err.response.status];
    } else {
      //请求没回来
      // 判断错误信息中是否包含timeout
      if (err.message.indexOf("timeout") > -1) {
        message = "网络超时，检查网络是否通畅";
        // 判断错误信息中是否包含Network
      } else if (err.message.indexOf("Network") > -1) {
        message = "断网了，查看网络是否链接";
      }
    }
    return Promise.reject(message);
  }
);

export default request;
